package core;

import java.util.Iterator;
import java.util.Set;

import db.Mapper;

import net.client.RequestDispacher;
import net.data.AskNamesRequest;
import net.data.FindNameRequest;
import net.data.SendNameRequest;

public class RequestBroadcaster
{
	private ChatNode node;
	
	public RequestBroadcaster(ChatNode node)
	{
		this.node = node;
	}
	
	public void broadcastFindName(String name, String fromAddress, int ttl)
	{
		Mapper userbase = node.getUserBase();
		if(userbase != null)
		{
			Set<String> names = userbase.getNames();
			
			int size = names.size();
			int n = 0;
			
			FindNameRequest[] requestArray = new FindNameRequest[size];
			
			Iterator<String> iter = names.iterator();
			while(iter.hasNext())
			{
				String currentName = iter.next();
				String currentAddress = userbase.getAddress(currentName);
				
				FindNameRequest request = new FindNameRequest();
				request.setToAddress(currentAddress);
				request.setFromAddress(fromAddress);
				request.setName(name);
				request.setTtl(ttl);
				
				requestArray[n] = request;
				n++;
			}
			
			RequestDispacher dispacher = new RequestDispacher(node);
			dispacher.dispach(requestArray);
		}
		
	}
	
	public void broadcastSendName(String name, String address, int ttl)
	{
		Mapper userbase = node.getUserBase();
		if(userbase != null)
		{
			Set<String> names = userbase.getNames();
			
			int size = names.size();
			int n = 0;
			
			SendNameRequest[] requestArray = new SendNameRequest[size];
			
			Iterator<String> iter = names.iterator();
			while(iter.hasNext())
			{
				String currentName = iter.next();
				String currentAddress = userbase.getAddress(currentName);
				
				SendNameRequest request = new SendNameRequest();
				request.setToAddress(currentAddress);
				request.setAddress(address);
				request.setName(name);
				request.setTtl(ttl);
				
				requestArray[n] = request;
				n++;
			}
			
			RequestDispacher dispacher = new RequestDispacher(node);
			dispacher.dispach(requestArray);
		}
	}
	
	public void broadcastAskNames(int ttl)
	{
		Mapper userbase = node.getUserBase();
		if(userbase != null)
		{
			Set<String> names = userbase.getNames();
			
			int size = names.size();
			int n = 0;
			
			AskNamesRequest[] requestArray = new AskNamesRequest[size];
			
			Iterator<String> iter = names.iterator();
			while(iter.hasNext())
			{
				String currentName = iter.next();
				String currentAddress = userbase.getAddress(currentName);
				
				AskNamesRequest request = new AskNamesRequest();
				request.setToAddress(currentAddress);
				request.setTtl(ttl);
				
				requestArray[n] = request;
				n++;
			}
			
			RequestDispacher dispacher = new RequestDispacher(node);
			dispacher.dispach(requestArray);
		}
	}
}
